package com.wisely.springbootjpa.service.users;

import com.wisely.springbootjpa.domain.User;
import com.wisely.springbootjpa.repository.UserJpaRepository;
import com.wisely.springbootjpa.repository.UserRepository;
import com.wisely.springbootjpa.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import static com.wisely.springbootjpa.criteria.CustomerSpecs.*;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserJpaRepository userJpaRepository;
    @Autowired
    private UserRepository userRepository;

    public List<User> findAll() {
        return userJpaRepository.findAll();
    }

    public List<User> findByName(String name) {
        List<User> userList1 = userRepository.findByName1(name);
        List<User> userList2 = userRepository.findByName2(name);
        List<User> userList3 = userRepository.findByNameAndAddress(name, "3");
        System.out.println("userList1:" + userList1);
        System.out.println("userList2:" + userList2);
        System.out.println("userList3:" + userList3);
        return userRepository.findByName(name);
    }

    @Override
    public List<User> findByNameLike(String name) {
        return userRepository.findByNameLike(name);
    }

    @Override
    public List<User> find10ByName(String name) {
        return userRepository.findFirst10ByName(name);
    }

    @Override
    public int updateUsernameById(String name, int id) {
        return userRepository.setName(name, id);
    }

    public void saveUser(User book) {
        userJpaRepository.save(book);
    }

    @Cacheable("users")
    public User findOne(long id) {
        System.out.println("Cached Pages");
        Optional<User> opt = userJpaRepository.findById(id);
        User user = opt.get();
        return user;
    }

    @Override
    public void delete(long id) {
        userJpaRepository.delete(findOne(id));
    }

    @Override
    public List<User> findFromBeijing() {
        return userJpaRepository.findAll(personFromBeijing());
    }

    @Override
    public List<User> findByNameAndDesc(String name) {
        return userRepository.findByName(name, new Sort(Sort.Direction.DESC, "age"));
    }

    @Override
    public List<User> findByNamePage(String name) {
        return userRepository.findByNamePage(name, new PageRequest(0,10));
    }
}
